package com.ocp.socket.server.mina;

import com.ocp.socket.common.utils.Des3;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.apache.mina.util.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.Charset;

/**
 * @Auther: zhangzh
 * @Date: 2019/1/23 16:38
 * @Description: 编码器将数据直接发出去(不做处理)
 * @Version: 1.0.0
 */
public class ByteArrayEncoder extends ProtocolEncoderAdapter {
    private static final Logger logger = LoggerFactory.getLogger(ByteArrayEncoder.class);
    private final Charset charset;

    public ByteArrayEncoder(Charset charset) {

        this.charset = charset;

    }

    /**

     * 直接将数据发出去,数据格式，包头+消息长度（int）+消息内容（json字符串）+包尾 包头包尾是十六进 制字符串00 aa bb cc,转化成字节数组0, * -86, -69, -52四个字节

     *

     * @param session

     * @param message

     * @param out

     * @throws Exception

     */

    @Override

    public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {

        String value = (message == null ? "" : message.toString()); // 消息值
        logger.debug("返回加密前：{}",value);
        byte[] msgStart = SocketManager.MESSAGE_START.getBytes(charset);
        byte[] msgEnd = SocketManager.MESSAGE_END.getBytes(charset);
        byte[] contentAndLen = SocketManager.getInstance().getMsgAndLen(value).getBytes(charset);
        byte[] contentEnCode = Des3.des3EncodeECB(SocketManager.KEY,contentAndLen);
        byte[] contentBASE64Encode = Base64.encodeBase64(contentEnCode);
        IoBuffer buf = IoBuffer.allocate(msgStart.length+contentBASE64Encode.length+msgEnd.length).setAutoExpand(true);
        logger.debug("返回加密后：{}{}{}", new String(msgStart), new String(contentBASE64Encode), new String(msgEnd));
        //包头
        buf.put(msgStart);
        //包体
        buf.put(contentBASE64Encode);
        //包尾
        buf.put(msgEnd);
        buf.flip();
        out.write(buf); // 写入
    }

}
